from randomizer import get_random_letter
from fatorial import fatorial


def calculate_permutation(list_lenght:int, repetitions_list:list) -> int:
    'calculate permutation with the formule.'

    res = 1
    for n in repetitions_list:
        res *= fatorial(n)
    res = fatorial(list_lenght)//res

    return res


def get_permutation_limit(word:str) -> int:
    'calculate permutation of word.'

    rep, history = [], []
    for letter in word:
        total = word.count(letter)
        if (letter not in history) and (total):
            rep.append(total)

            history.append(letter)

    return calculate_permutation(len(word), rep)


def get_permutation(word:str, force_list:bool = False) -> str:
    'returns the possible permutation of a word.'

    history = []
    while len(history) < get_permutation_limit(word):
        new_word = ''
        letter_history = {}

        while len(new_word) < len(word):
            letter = get_random_letter(word)
            if letter in letter_history:
                letter_history[letter] += 1
            else:
                letter_history[letter] = 1
                new_word += letter
                continue

            if letter_history[letter] <= word.count(letter):
                new_word += letter

        if new_word not in history:
            history.append(new_word)
            if not force_list:
                yield new_word

if __name__ == "__main__":
    from sys import argv as args
    for p in get_permutation(args[1]):
        print(p)
